#include "threadPool.h"

void puts_file(int netfd, MYSQL *db,char *Data, char *realPath, char *cur_user_pwd,int cur_dirid, int user_id){
    TLV tlv;
    //接收md5
    char md5[256] = {0};
    recv(netfd,&tlv.length,sizeof(tlv.length),0);
    recv(netfd,&tlv.tag,sizeof(tlv.tag),0);
    recv(netfd,tlv.data,tlv.length,0);
    memcpy(md5,tlv.data,tlv.length);
    md5[tlv.length] = '\0';
    //拼接真实路径
    char real_pathname[256] = {0};
    strcpy(real_pathname,realPath);
    strcat(real_pathname,md5);
    //查询是否存在文件
    char query[1024];
    sprintf(query,"select count(*) from virturefiletable where md5 = '%s';",md5);
    mysql_query(db, query);
    printf("开始查询是否存在md5文件，执行了sql语句：%s\n",query);
    MYSQL_RES *Res = mysql_use_result(db);
    MYSQL_ROW Row = mysql_fetch_row(Res);
    //                mysql_free_result(res);
    int is_intact = 1;
    int not_intact  = 0;
    if(atoi(Row[0]) == 0){
        mysql_free_result(Res);
        printf("不存在，  %d\n",atoi(Row[0]));
        //告诉客户端可以开始传文件了
        send(netfd,&not_intact,sizeof(int),MSG_NOSIGNAL);
        printf("%s\n",real_pathname);
        recvfile(netfd,real_pathname);
        char hash[256];
        hash_compute(hash,real_pathname);
        printf("%s   %s\n",hash,md5);
        if(strcmp(hash,md5) == 0){
            printf("文件校验成功，传输的是完整的文件，写入数据库------------------\n");
            sprintf(query,"INSERT INTO virturefiletable (parent_id, filename, owner_id, md5, path, type, status)VALUES(%d, '%s', %d, '%s', '%s', 'f', 'exist');",cur_dirid,Data,user_id,md5,cur_user_pwd);
            mysql_query(db,query);
        }

        //        recvfile(netfd,real_pathname);
    }
    else{
        mysql_free_result(Res);
        //告诉客户端已经有了，不用传了
        send(netfd,&is_intact,sizeof(int),MSG_NOSIGNAL);
        sprintf(query,"select count(*) from virturefiletable where owner_id = 1 and status = 'exist' and md5 = '%s';",md5);
        mysql_query(db, query);
        printf("执行了sql语句：%s\n",query);
        Res = mysql_use_result(db);
        Row = mysql_fetch_row(Res);
        //                mysql_free_result(res);
        if(atoi(Row[0]) == 0){
            mysql_free_result(Res);
            sprintf(query,"INSERT INTO virturefiletable (parent_id, filename, owner_id, md5, path, type, status)VALUES(%d, '%s', %d, '%s', '%s', 'f', 'exist');",cur_dirid,Data,user_id,md5,cur_user_pwd);
            printf("执行了sql语句：%s\n",query);
            mysql_query(db,query);
            printf("此次进行的是秒传，未调用recvfile-------------------\n");
        }
        else{
            mysql_free_result(Res);
        }
    }


    close(netfd);
    mysql_close(db);
}


